text:
Q: Implementing and running a 3D U-net for denoising of synthetic data I'm building a u-net for denoising some synthetic images over time. My data is (256,256,128,1) which is 256*256 grayscale images over 128 time-steps(trajectory is random cosin). I have 120 images, so the whole dataset is of shape (120,256,256,128,1). I've added 5% random noise to this data for getting the noisy dataset. I'm using TF2 and I'm treating it more like Keras since I've just started.
Here's a summary of my data:
x_train (120, 256, 256, 128, 1)
x_train_noisy (120, 256, 256, 128, 1)
x_validation (10, 256, 256, 128, 1)
x_validation_noisy (10, 256, 256, 128, 1)
x_test (10, 256, 256, 128, 1)
x_test_noisy (10, 256, 256, 128, 1)
x_train_input (100, 256, 256, 128, 1)
x_train_noisy_input (100, 256, 256, 128, 1)

Now I wanna build a 3D u-net for denoising it. Where I give the noisy images as input and the original demonised as desired output and want it to learn the transformation. I'm new to this, so I used a simple 2d unet from github as a kind of template and adapted it.
-Here's my U-net: I want to know (1) If this u-net architecture is correct? (anything obviously wrong with it, etc?)(it's basically a normal u-net like the Ronnenberg one).
inputs = Input((256,256,128,1))

conv1 = Conv3D(64, (3,3,3), activation='relu', padding='same')(inputs)
conv1 = Conv3D(64, (3,3,3), activation='relu', padding='same')(conv1)
pool1 = MaxPooling3D(pool_size=(2,2,2))(conv1)

conv2 = Conv3D(128, (3,3,3), activation='relu', padding='same')(pool1)
conv2 = Conv3D(128, (3,3,3), activation='relu', padding='same')(conv2)
pool2 = MaxPooling3D(pool_size=(2,2,2))(conv2)

conv3 = Conv3D(256, (3,3,3), activation='relu', padding='same')(pool2)
conv3 = Conv3D(256, (3,3,3), activation='relu', padding='same')(conv3)
pool3 = MaxPool3D(pool_size= (2,2,2))(conv3)

conv4 = Conv3D(512, (3,3,3), activation='relu', padding='same')(pool3)
conv4 = Conv3D(512, (3,3,3), activation='relu', padding='same')(conv4)

up4 = concatenate([Conv3DTranspose(256, (3,3,3), strides=(2,2,2), padding ='same')(conv4), conv3], axis=-1)

conv5 = Conv3D(256, (3,3,3), activation='relu', padding='same')(up4)
conv5 = Conv3D(256, (3,3,3), activation='relu', padding='same')(conv5)

up5 = concatenate([Conv3DTranspose(128, (3,3,3), strides=(2,2,2), padding='same')(conv5), conv2], axis=-1)

conv6 = Conv3D(128, (3,3,3), activation='relu', padding='same')(up5)
conv6 = Conv3D(128, (3,3,3), activation='relu', padding='same')(conv6)

up6 = concatenate([Conv3DTranspose(64, (3,3,3), strides=(2,2,2), padding ='same')(conv6), conv1], axis=-1)

conv7 = Conv3D(64, (3,3,3), activation='relu', padding='same')(up6)
conv7 = Conv3D(64, (3,3,3), activation='relu', padding='same')(conv7)

conv8 = Conv3D(1, (3,3,3), activation=None, padding='same')(conv7)

conv9 = Activation('relu')(conv8)

#now the keras Model and compilation
unet = Model(inputs = [inputs], outputs = [conv9])
unet.compile(optimizer = 'adam', loss = 'mean_squared_error')

-Now I'm trying to fit it:
    save_dir = "/Users/Jack/Desktop/unet_50"

es_cb = EarlyStopping(monitor='val_loss', patience=2, verbose=1, mode='auto')
chkpt = save_dir + 'unet_50_synthetic_denoise_weights.{epoch:02d}-{loss:.2f}-{val_loss:.2f}.hdf5'
cp_cb = ModelCheckpoint(filepath = chkpt, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
tensor_board = tf.keras.callbacks.TensorBoard(
                log_dir = "my_log_dir_unet_50",
                histogram_freq = 1,
                embeddings_freq = 1,)

history = unet.fit(x_train_noisy_input, x_train_input,
                   batch_size = 4,
                   epochs = 100,
                   verbose=1,
                   validation_data=(x_validation_noisy, x_validation),
                   callbacks = [es_cb, cp_cb],
                   shuffle=True)

-But I get this and it's been stalling like this for about an hour like this. I'm pretty sure there should be something like a progress bar going through epochs:
Train on 100 samples, validate on 10 samples
Epoch 1/100

-So here's what my questions:
What am I doing wrong that the fit is stalling( is it that it should take hours and the progress bar thing is simply lagging behind). I know that my computer(CPU) is definitely running something heavy.
-Do you see anything wrong with the u-net code?
-Regarding the batch size, and the splitting of data for validation, do you see any obvious mistake or a  way better way to choose the numbers?

A: The size of the input you feed to your network (256x256x128 images) is enormous, on top of that you have 64 layers on the first level of your architecture. I guess, only taking into account the conv layers of the first level should allready aggregate into something like 10 to 100Gb of GPU memory which is way too big.
I guess that's the reason why it got stuck, I am surprised though that it does not broadcast any kind of error message such as GPU memory overflow.
I would recommand to decrease the number of layers of the first levels, and to change them with 2d (3,3,1) kernels (the kernel will only works on the dimensions of the images and not on the dimension of the time).


text:
Q: Window Phone 7 C# pass paramters in a routedeventhandler I'm trying to pass parameters to a function that is used in a RoutedEventHandler
Button start = new Button();
start.Click += new RoutedEventHandler(playSelectedAlarm_Click);

private void playSelectedAlarm_Click(object sender, EventArgs e)
{
    NavigationService.Navigate(new Uri("/AlarmPicker.xaml", UriKind.Relative));
}

how do I do this? Or is there a better way?

A: You could add your parameters into the Button's Tag property. Then, extract them in your event handler:
Button start = new Button();
start.Tag = new string[] { "param1", "param2" };
start.Click += new RoutedEventHandler(playSelectedAlarm_Click);

private void playSelectedAlarm_Click(object sender, EventArgs e)
{
    //extract the parameters and cast to a `string[]`
    var myParameters = (string[])((Button)sender).Tag;
    string p1 = myParameters[0]; //value is "param1"
    string p2 = myParameters[1]; //value is "param2"

    NavigationService.Navigate(new Uri("/AlarmPicker.xaml", UriKind.Relative));
}

The Tag property expects an object type, so you can input an array of parameters, collection, string etc..

A: Change your :
NavigationService.Navigate(new Uri("/AlarmPicker.xaml", UriKind.Relative));

to
var uri = "/AlarmPicker.xaml?idx=" + url + "&title=" + title);
NavigationService.Navigate(new Uri(uri, UriKind.Relative));

After that, in your AlarmPicker.xaml.cs add this:
out string m_Link = string.empty;
out string m_Title = string.empty;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    NavigationContext.QueryString.TryGetValue("idx", out m_Link);
    NavigationContext.QueryString.TryGetValue("title", out m_Title);

    Console.Writeline("IDX: " + m_link);
    Console.Writeline("TITLE: " + m_Title);
}

It's called when you load AlarmPicker.xaml!
It's used to get passed values, like a query string.
hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android support v7 SpinnerICS outside of ActionBar I converted some code from ActionBarSherlock to ActionBar Compat using android support v7 appcompat library.
My ActionBar code is working fine.  But I also had some ActionBarSherlock IcsSpinners outside of ActionBar in my fragment and I wanted those spinners to be the same ICS style as before with ActionBarSherlock. So I copied the internal support v7 library SpinnerICS files out of the support library since they are private and we can not use them directly and put them into my own tree.
But when I convert these IcsSpinners to SpinnerICS they no longer work as they did under ActionBarSherlock.  I see a spinner label next to the first item in the list but the little spinner triangle does not appear and pressing the item does not trigger the listener as I've tested with logging.
Here's where I copied the SpinnerICS files in my project(you may have to adjust R. package):
$ ls -1 widget/
AbsSpinnerICS.java
AdapterViewICS.java
ListPopupWindow.java
SpinnerICS.java

Here's what the fragment code looks like:
public class Fragment1 extends Fragment {

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            ...
            SpinnerICS spinner = (SpinnerICS) view.findViewById(R.id.spinner1);

            spinner.setOnItemSelectedListener( new AdapterViewICS.OnItemSelectedListener() {
                    public void onItemSelected(AdapterViewICS<?> parent, View view, int pos, long id) {

                            if (pos > 0) { var = (String) parent.getItemAtPosition(pos); }
                            else         { var = null; }
                            Log.v(TAG, String.format("Fragment1: onItemSelected: pos: %d var: %s", pos, var));
                    }

                    public void onNothingSelected(AdapterViewICS<?> parent) {
                    }
            });
            ...
            return view;
    }

onActivityCreated(...) {
    ...
    adapter = new ArrayAdapter( getActivity(), android.R.layout.simple_spinner_item, list );
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    ...
}

Has anyone got these SpinnerICS widgets working outside of ActionBar?


text:
Q: Add a texture on a sphere by Urhosharp I'm using Xamarin.Forms + Urhosharp, I've got a problem to set texture from an image on a sphere. The problem is that texture.Load or texture.SetData always returns false. I did try different methods like SetData, Load, resize texture and image (to a power of 2 number) and ... but none of them worked. Here is my code:
    private async void CreateScene()
    {
        Input.SubscribeToTouchEnd(OnTouched);

        _scene = new Scene();
        _octree = _scene.CreateComponent<Octree>();

        _plotNode = _scene.CreateChild();
        var baseNode = _plotNode.CreateChild().CreateChild();
        var plane = baseNode.CreateComponent<StaticModel>();
        plane.Model = CoreAssets.Models.Sphere;

        var cameraNode = _scene.CreateChild();
        _camera = cameraNode.CreateComponent<Camera>();
        cameraNode.Position = new Vector3(10, 15, 10) / 1.75f;
        cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);

        Node lightNode = cameraNode.CreateChild();
        var light = lightNode.CreateComponent<Light>();
        light.LightType = LightType.Point;
        light.Range = 100;
        light.Brightness = 1.3f;

        int size = 3;
        baseNode.Scale = new Vector3(size * 1.5f, 1, size * 1.5f);

        var imageStream = await new HttpClient().GetStreamAsync("some 512 * 512 jpg image");
        var ms = new MemoryStream();
        imageStream.CopyTo(ms);

        var image = new Image();
        var isLoaded = image.Load(new MemoryBuffer(ms));
        if (!isLoaded)
        {
            throw new Exception();
        }

        var texture = new Texture2D();
        //var isTextureLoaded = texture.Load(new MemoryBuffer(ms.ToArray()));
        var isTextureLoaded = texture.SetData(image);
        if (!isTextureLoaded)
        {
            throw new Exception();
        }

        var material = new Material();
        material.SetTexture(TextureUnit.Diffuse, texture);
        material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0);
        plane.SetMaterial(material);

        try
        {
            await _plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 0, 360, 0)));
        }
        catch (OperationCanceledException) { }
    }

Please help!

A: To Create a material from a 2D Texture, you can use Material.FromImage .
Refer following documentation for more detail.
model.SetMaterial(Material.FromImage("earth.jpg"));

https://developer.xamarin.com/api/type/Urho.Material/
https://developer.xamarin.com/api/member/Urho.Material.FromImage/p/System.String/
private async void CreateScene()
{

   _scene = new Scene();
   _octree = _scene.CreateComponent<Octree>();

   _plotNode = _scene.CreateChild();
   var baseNode = _plotNode.CreateChild().CreateChild();

   var plane = _plotNode.CreateComponent<StaticModel>();
   plane.Model = CoreAssets.Models.Sphere;
   plane.SetMaterial(Material.FromImage("earth.jpg"));

   var cameraNode = _scene.CreateChild();
   _camera = cameraNode.CreateComponent<Camera>();
   cameraNode.Position = new Vector3(10, 15, 10) / 1.75f;

   cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);

   Node lightNode = cameraNode.CreateChild();
   var light = lightNode.CreateComponent<Light>();
   light.LightType = LightType.Point;
   light.Range = 100;
   light.Brightness = 1.3f;

   int size = 3;
   baseNode.Scale = new Vector3(size * 1.5f, 1, size * 1.5f);

   Renderer.SetViewport(0, new Viewport(_scene, _camera, null));

   try
   {
       await _plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 0, 360, 0)));
   }
   catch (OperationCanceledException) { }

}


text:
Q: On which basis we think there is something more than just super dense matter in black holes? Apparently physicists think that there is something inside black holes. Like a new universe or a link between dimension... But for me a black hole is no more than supermassive supercompacted matter. So my question is on which theoretical or observational bases these theory of what is inside a black hole lie on?
thanks!
(yes, I've seen Interstellar few days ago)

A: You are correct that physicists think a black hole is a link to another universe.
No, not really, that's just an attention grabbing headline. Physicists (most of them) don't believe black holes are links to other universes, apart from some fringe theories that I'll come back to. But let me explain where this misconception comes from. This absolutely fascinated me as a spotty youth - who wouldn't be fascinated by the idea that multiple universes might be real - so I'll spend a bit of time trying to explain this layman's terms. This will make the answer a bit long, but I think it's worth sticking with it.
The first, and key, thing to note is that real black holes are fearsomely complicated objects, so physicists tend to use simplified models of black holes. The simplest model, and the one we learn first, is the Schwarzschild metric. If you're describing things around a black hole the simplest way to approach this is consider distance from the centre, which we call $r$, and time, which we call $t$. If something is falling into a black hole we expect the distance $r$ to decrease with time and become zero at the moment you splat into the centre. So if we draw a graph to show something falling into the black hole it might look like:

This shows time $t$ on the vertical scale, so increasing time moves up. The distance from the centre is on the horizontal scale.
Now we can define a zero of time whenever we want. For example the zero of our calendar is at midnight on the year zero AD. Times before this are shown as negative (or BC if it's a calendar). That's why I've put the zero of the time axis in the middle so time is positive in the top half and negative in the bottom half. However distance from the centre can only be positive because you can't get closer to the centre than zero. It doesn't make sense to have negative values of $r$, and that's why I've drawn the distance axis starting at zero.
So far so good, but it turns out that by choosing $r$ and $t$ as our coordinates we have oversimplified the physics of the black hole. In 1960 a couple of physicists called Martin Kruskal and George Szekeres discovered that to fully describe the black hole you need to use different coordinates called (unsurprisingly) Kruskal-Szekeres coordinates. These have a coordinate $u$ that is sort of like distance, and a coordinate $v$, that is sort of like time. But when you draw a graph like the one above you find that both $u$ and $v$ can be negative as well as positive, and a graph of an object falling into the black hole looks like:

Explaining this diagram fully would take ages, so I'm going to cop out and just say that region ${\bf 1}$ is just the regular spacetime where we live, and region ${\bf 2}$ is inside the black hole event horizon. The curious thing is that our diagram now contains extra regions ${\bf 3}$ and ${\bf 4}$, and region ${\bf 3}$ is a region of ordinary spacetime just like ours, but which we can never get to.
So the Kruskal-Szekeres diagram shows two universes, regions ${\bf 1}$ and ${\bf 3}$, and they are joined by a type of wormhole called an Einstein-Rosen bridge. As it turns out nothing can cross the Einstein-Rosen bridge without travelling faster than light, and since that's impossible it means the two universes are forever isolated from each other. Still, the other universe is there.
In fact it gets even weirder than this. If we put an electrical charge on our black hole we get a Reissner-Nordström black hole, and this does allow you to travel to the other universes. I discussed this in my answer to the question Entering a black hole, jumping into another universe---with questions.
A rotating black hole does something similar, though the geometry is more complicated.
But I did say right at the outset that physicists don't really believe these other dimensions exist, which is sad and which was a great disappointment to me when I started learning general relativity - oh well.
The trouble is that the Schwarzschild metric I started with is a simplified model. For one thing it only applies if the black hole is unchanging i.e. it must have existed unchanged for an infinite time and must exist unchanged for an ininite time into the future. But we know no black hole can't be older than 13.7 billion years because that's how old the universe is. And we know black holes will eventually evaporate due to Hawking radiation, so they can't last an infinite time into the future.
And that spoils all the fun. It turns out a black hole of a finite age (probably) doesn't contain the extra regions of spacetime so there are no extra universes. The reason why you've heard about extra universes is because this subtlety tends to be lost on the popular press, science fiction writers and other groups with only a partial understanding of relativity. And of course because having extra universes is much more fun than not having extra universes!
I did say there were some fringe theories about black holes being gateways to other universes. This started in the late 60s with the work of a Russian physicist called M. A. Markov (I'm not sure what the M. A. stands for), who discovered that the spacetime describing a black hole could be seamless joined up to the spacetime describing an expanding universe. This is discussed to some extent in my answer to the question How does the friedmon solution to Einstein's equations resolve paradox of bounded infinities?. If you fell into a spacetime with this geometry you'd start by falling towards what looked like a black hole and certain death, but then you'd find you were drifting in an expanding universe just like ours.
But this is just a piece of clever geometry, and there was no physical model for why this particular geometry might actually exist. In the absence of any such model the obvious conclusion is that it doesn't. However some time later the American physicist Lee Smolin picked up the idea and proposed that it could happen due to quantum gravity effects, and that black holes really were gateways to new expanding universes. Smolin's theories are described in his book The Life of the Cosmos. Personally I don't believe a word of it, though I recommend the book as it's relatively easy reading and very entertaining.

A: There is no basis for such speculation. General relativity defines the event horizon of a black hole as the boundary from which nothing -- no matter, no light, no information -- can ever escape. Thus the question of what is inside a black hole becomes rather moot. The answer cannot even in principle affect us outside the event horizon.
Now black holes are fascinating objects, and some physicists debate endlessly about what happens when we throw quantum mechanics into the mix. But there are scarce few results from this line of thinking, other than some suggestions that maybe the universe only forms transient things that are very close to but not quite the ideal black holes we like to think about.
Certainly there is no observational evidence to speak of in this matter -- everything we could conceivably measure about real black holes with anything like our current technology is perfectly well explained without quantum effects.
As for new universes and other dimensions: These words get thrown around a lot in science fiction, but they don't mean much in science. If you go with the simple "everything that can be observed" definition of "universe," then by definition there can be no other universe to observe. So you'd have to come up with some other definition to even make sense of the idea of another universe. And "dimensions" just refers to how many space (3) and time (1) coordinates one needs to specify a location in the universe, rather than a "plane of existence" or whatever science fiction might use the term for.


text:
Q: Why is body-parser struck thru w/ line in my VSCode and how to get it to function? Building a MERN CRUD app and read thru StackOverflow. Saw body-parser has been deprecated. Followed additional instructions and still getting line strike. Does this line strike thru body-parser matter? Does this mean body-parser is not functioning for my code? Thanks for taking the time to read my question. Much appreciated.
dependencies
body-parser with line strike thru

A: Found answer to my question: body parser use to be built into express core library. Then, they separated body parser. The newest update to express has gone back to the older arrangement of including body parser shipping with core express library.
Old way:
app.use(bodyparser.urlencoded({ extended: true}))
Latest version as of 2021 way:
app.use(express.urlencoded({ extended: true}))


text:
Q: How do I generate build-info.properties in the IntelliJ "out" directory on debug/run for a Spring Boot project? In my build.gradle, I have added spring build info:
springBoot {
    mainClass = "${springBootMainClass}"

    buildInfo() {
        additionalProperties = [
                name: "${appName}",
                version: "${version}-${buildNumber}",
                time: buildTime()
        ]
    }
}

def buildTime() {
    final dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
    dateFormat.timeZone = TimeZone.getTimeZone('GMT')
    dateFormat.format(new Date())
}

When I run from the command line, this correctly adds the /META-INF/build-info.properties file into /build/resources/main so that the "/info" endpoint shows the build information in JSON.
When I run from IntelliJ's run/debug button, IntelliJ does not use the /build directory but instead uses the /out directory and also does not run that gradle task, so the /info endpoint has empty JSON.
How can I make it generate that file and put it in the /out directory?

A: I have exactly the same need, and I don't want to use "delegate IDE build/run action to Gradle" for different (good) reasons.
In my case I don't need that file /META-INF/build-info.properties to be up-to-date in IDEA during develop phase, I just need this file to be available in the "run" classpath (under /out/...), else Spring won't be able to create and inject the BuildProperties bean when launching my app from IDEA run/debug tool.
So here is a simple solution if your are also in my case:

*

*create a dummy "dev" (or "snapshot") version of the build-info.properties in the main resources directory  ( src/main/resources/META-INF/build-info.properties )
#DO NOT EDIT (will be overriden by Spring boot plugin )
build.time=2019-05-07T11:32:31.581Z
build.artifact=myapp
build.group=org.mycompany
build.name=myapp
build.version=dev
This dev version will be automatically copied into IDEA /out/production/resources directory when building project from IDEA

*Create a task dependency between bootBuildInfo task and processResources tasks, to make sure that Spring boot plugin will override the "dev" version with up-to-date version when building the app jar:
bootBuildInfo.mustRunAfter processResources
This way, SpringBoot gradle plugin will override the file copied from sources by processResources task, with its auto-generated up-to-date file.
EDIT 2020-10
As Dmitry warned in comment below, this solution will break Gradle incremental build, as both processResources and bootBuildInfo tasks share the same output file build-info.properties. To avoid that, we can add exclusion in the processResources to filter out this file, when we detect that tasks graph contains bootBuildInfo  tasks
project.gradle.taskGraph.whenReady {
    if (it.allTasks.any {it.name == "bootBuildInfo"}) {
        processResources {
            exclude("META-INF/build-info.properties")
        }
    }
}

A: Enable Delegate IDE build/run actions to Gradle option in Settings (Preferences) | Build, Execution, Deployment | Build Tools | Gradle | Runner tab.
In latest IDE versions set Gradle for the Settings (Preferences on macOS) | Build, Execution, Deployment | Build Tools | Gradle | Build and run using option.

A: For anyone else with this problem in IntelliJ IDEA Community Edition (where the option @Andrey said does not exist), you just have to add a Run Maven Goal before launch. This will execute the goal of the plugin: spring-boot:build-info before build and run


text:
Q: Javascript: execcommand fontsize in px all.. I do know that this question is kind of scattered over the internet, but nothing seems to be pointing me right.
I am making my own wysiwyg and the problem I'm facing is that the code
document.execCommand("fontSize", false, value);

accepts only values from 1 to 7 (inclusive) to be assigned to the "size" attribute of "font" tag. However I need to set the font-size in pixels.
I found this example in a similar stackoverflow question. But the problem with this approach is that it only changes the font-size for the selected text. if you aim to set the font-size before typing your text, it will not work.
Does any one have any idea how I can solve this?

A: You could use a hacky method, such as calling document.execCommand("fontSize", false, "7"); and then finding the elements the command has created and changing them as required. See example: http://jsfiddle.net/S3ctN/.
This obviously depends on there being no other  elements with size 7 in the document and it also relies on the browser using  elements for font size, which it seems they all do
document.execCommand() FontSize in pixels?


text:
Q: A manga about a man in a slice-of-life isekai manga about eating otherworld foods It's a black and white manga, with not many chapters, maybe 50-ish at max, where a black-haired dude (main character) and his maid (female MC) go around eating foods like dragon steak to a magic water apple. She likes him, and the MC's goal is to basically eat every rare otherworld food he can.

A: This is Gourmet in a Different World (AKA Gensou Gourmet).
The main character travels the world with his maid eating exotic foods. The first chapter is about him having dragon steak and the 11th is about him eating water fruits.


text:
Q: Jsonwebtoken Verify is causing a 500 server error in Express I'm trying to verify/decode JWTs in my application but am running into an issue, and I have no idea why. Here is the function which is supposed to achieve this, but is creating a 500 server error:
exports.index = (req, res, next) => {
  let token = req.headers.authorization;
  let decoded = jsonwebtoken.verify(token, process.env.SECRET);
  console.log(decoded);
  res.send(decoded);
}

req.headers.authorization is correctly storing and delivering the Bearer token, and process.env.SECRET is the same key that was used to sign the token. I am importing the jsonwebtoken library. I'm stumped. Any help is appreciated.
EDIT: Just wrapped the function in a try/catch and the error that is raised is:
JsonWebTokenError: invalid token
at Object.module.exports [as verify] (/Users/-------/repos/sosh/node_modules/jsonwebtoken/verify.js:75:17)
at exports.index (/Users/-------/repos/sosh/controllers/soshController.js:15:32)
at Layer.handle [as handle_request] (/Users/--------/repos/sosh/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/-------/repos/sosh/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/--------/repos/sosh/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/-------/repos/sosh/node_modules/express/lib/router/layer.js:95:5)
at /Users/-------/repos/sosh/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/------/repos/sosh/node_modules/express/lib/router/index.js:335:12)
at next (/Users/-------/repos/sosh/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/------/repos/sosh/node_modules/express/lib/router/index.js:174:3)

I'm wondering why it says invalid token - I use this same token in my JWT authentication strategy and it works fine. Its formatted as "Bearer j5asdj........".


text:
Q: Spring Boot @Autowired creating instances on a runtime As most of Spring Boot new users I have a problem with @Autowired :D
I've readed a big amount of topics about this annotation here But still can't find proper solution for my problem.
Let's suppose that we have this Spring Boot hierarchy:
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Class, that we wanna instantiate every time it's called:
@Service
public class TestWire {
    public TestWire() {
        System.out.println("INSTANCE CREATED: " + this);
    }
}

Out get controller, that creates new SomeRepo object every request:
@RestController
public class CreatingRepo {
    @RequestMapping("/")
    public void postMessage() {
        SomeRepo repo = new SomeRepo();
    }
}

Finally, class, that uses @Autowired to create  TestWire instances:
public class SomeRepo {
    @Autowired
    private TestWire testWire;

    public SomeRepo() {
        System.out.println(testWire.toString());
    }
}

Let's assume, that we make GET request to "/" several times.
So, as a result, TestWire class will isntantiate only when project builds and neither @Scope(value = "prototype"), nor proxyMode = ScopedProxyMode.TARGET_CLASS wont help.
Any ideas how to create new instances at runtime? I mean, how can we do it in "Spring way"? Without factories and other things, only Spring DI through annotation and configuration.
Upd. A piece of stack trace, where instance created:
2015-11-16 20:30:41.032  INFO 17696 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
INSTANCE CREATED: com.example.TestWire@56c698e3
2015-11-16 20:30:41.491  INFO 17696 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12f41634: startup date [Mon Nov 16 20:30:37 MSK 2015]; root of context hierarchy
2015-11-16 20:30:41.566  INFO 17696 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public void com.example.CreatingRepo.postMessage()

A: If I understood you correct you need to annotate the SomeRepo like this:
@Service
@Scope(value = "prototype")
public class SomeRepo {
// ...
}

Option A:
Instead of instantiating the class with new SomeRepo(); you ask the BeanFactory.getBean(...) for it.
@RestController
public class CreatingRepo {
    @Autowired
    BeanFactory beanFactory;

    @RequestMapping("/")
    public void postMessage() {
        // instead of new SomeBean we get it from the BeanFactory
        SomeRepo repo = beanFactory.getBean(SomeRepo.class);
    }
}

Option B:
You should also be able to get the Bean like this (over paramters without the beanFactory):
@RestController
public class CreatingRepo {

    @RequestMapping("/")
    public void postMessage(SomeRepo repo) {
        // instead of the BeanFactory and using new SomeRepo you can get it like this.
    }
}


text:
Q: Does very short TTL in Cassandra data lead to performance problems? For our real high traffic site we've set up a own tracking solution. We log >1k impressions per second in peak. For that we're using latest Cassandra 3.
Now we want to set up a real time monitoring on this data. The problem is, that the actually logged data is not structured well for generating statistics from it. So I thought about a new table in Cassandra which has a matching partition/primary key and that is filled by an additional INSERT. But I'm not sure if this is a killer for Cassandra. As I've said, only live statistics are important, so I want to add a TTL of, let's say 60 seconds to all data in this monitoring table. This should ensure that old data is deleted automatically.
But can anyone say if this leads to problems with this high traffic, because there where so many deletions per minute? As we select only last 5-10 seconds from this monitoring table, the tombstone may not be a problem in SELECT, but I assume there could be massive compactions and GC that ruin the performance!?

A: Yes, apparently it would.
Having a short TTL means introducing too many tombstone in your system which may result in:
1.query abortion
2.out of memory and heap pressure
3.Latency
in such case you should run compaction very frequently to evict out tombstone from system but this also comes with cons of resource, space consuming and can cause high IO.


text:
Q: How to enforce a one-many relationship between a column in one table and a column in two parent tables? I have three tables in an existing database application.  I don't have ERDs or other documentation about the table relations.  There are no existing primary or foreign keys.
I would like to model the relation and ideally enforce it with constraints.
The order table can have any number of orders for parts.  The value of the Orders.part column must exist in either the Parts_inv table or the Parts_noninv table.  I would think the original design should have had one parts table with a type column, but this what I have. Is there a way to model/enforce these relationships?
Orders
order     char(10)
part      char(20)

Parts_inv
part_num  char(50)

Parts_noninv
part_num  char(50)

A: Given just the tables you have you can't do this. But that's not to say it can't be done. :-)
Ideally you should change ORDER.PART to CHAR(50) to match the PARTS_NUM fields on the other tables - otherwise you won't be able to store all the possible PARTS_NUM on an ORDER. Perhaps there are business reasons for it being as it is, and perhaps someone was just clueless. No matter - try to fix it up if you can. It won't stop you completely, though.
Create another table - let's call it PARTS_ALL. It has two fields - PARTS_NUM which should match the data type of the PARTS_NUM fields on PARTS_INV and PARTS_NONINV, and SOURCE which should be VARCHAR2(1). Make the combination of (PARTS_NUM, SOURCE) the primary key. So it looks like
CREATE TABLE ALL_PARTS
  (PARTS_NUM   CHAR(50),
   SOURCE      VARCHAR2(1) NOT NULL,
   CONSTRAINT PK_ALL_PARTS
     PRIMARY KEY (PARTS_NUM, SOURCE));

You then copy the data from PARTS_INV and PARTS_NONINV into ALL_PARTS, adding the appropriate SOURCE value:
INSERT INTO ALL_PARTS (PARTS_NUM, SOURCE)
  SELECT PARTS_NUM, 'I' AS SOURCE FROM PARTS_INV
  UNION ALL
  SELECT PARTS_NUM, 'I' AS SOURCE FROM PARTS_NONINV

Now you define a couple of triggers on PARTS_INV and PARTS_NONINV to propagate inserts and deletes on those tables to ALL_PARTS:
CREATE TRIGGER PARTS_INV_AID
  AFTER INSERT OR DELETE ON PARTS_INV
  FOR EACH ROW
BEGIN
  IF INSERTING THEN
    INSERT INTO ALL_PARTS (PARTS_NUM, SOURCE) VALUES (:NEW.PARTS_NUM, 'I');
  ELSIF DELETING THEN
    DELETE FROM ALL_PARTS WHERE PARTS_NUM = :OLD.PARTS_NUM;
  END IF;
END PARTS_INV_AID;
/

CREATE TRIGGER PARTS_NONINV_AID
  AFTER INSERT OR DELETE ON PARTS_NONINV
  FOR EACH ROW
BEGIN
  IF INSERTING THEN
    INSERT INTO ALL_PARTS (PARTS_NUM, SOURCE) VALUES (:NEW.PARTS_NUM, 'N');
  ELSIF DELETING THEN
    DELETE FROM ALL_PARTS WHERE PARTS_NUM = :OLD.PARTS_NUM;
  END IF;
END PARTS_NONINV_AID;
/

Now your application suite can continue to INSERT and DELETE rows from PARTS_INV and PARTS_NONINV as they've always done, and those changes will be propagated to ALL_PARTS.
NOW (finally!) you can define your foreign key from ORDERS to ALL_PARTS and get the validation you wanted:
ALTER TABLE ORDER
  ADD CONSTRAINT ORDER_FK1
    FOREIGN KEY (PART) REFERENCES ALL_PARTS (PARTS_NUM);

Is this ideal? No. IDEALLY you'd get rid of PARTS_INV and PARTS_NONINV, and replace them with ALL_PARTS, modifying all your applications and web apps and back-office software to use the new table - so probably not gonna happen - but given the situation you find yourself in it may be about as good as you can do.
dbfiddle here

A: Here's one way to achieve this, using a materialized view.
In my full working example, I create two tables, T1 and T2. Each has an ID column, and another column that is not the same in the two tables (NAME in one, PRICE in the other, not even the same data type). The task is to create a primary key from the UNION ALL of columns ID from both tables.
First, ID must be PK in each table. Then we create a materialized view (MV) from the UNION ALL of the ID columns from the two tables, and declare the column ID in the MV as the primary key of the MV. Then, in the last step, I create a child table T, with a column ID, foreign key pointing to the MV (not to T1 or T2, but the union all of the ID's from both tables).
You may want to test various things that you could do with the three tables (T1, T2 and T) to see how this all works.
Two things to keep in mind: (1) PK and FK constraints on tables are usually checked at INSERT / UPDATE / DELETE time (if the constraints are "immediate"); this will be the case for the PK constraints on ID, separately for T1 and T2. However, the joint PK constraint on the MV is only checked at COMMIT time. The FK constraint on table T is checked "immediate" (after each INSERT, UPDATE or DELETE - or MERGE - statement). (2) Checking the PK constraint on the MV adds marginal overhead to DML statements on T1 and T2.
So, here goes:
create table t1 (id number primary key, name varchar2(100));
create table t2 (id number primary key, price number not null);

create materialized view log on t1 with primary key, rowid including new values;
create materialized view log on t2 with primary key, rowid including new values;

create materialized view t12 (id, rid, source)
refresh fast on commit
as
select id, rowid, 't1' from t1 union all select id, rowid, 't2' from t2
;

alter materialized view t12 add constraint t12_pk primary key (id);

create table t (id number references t12, eff_date date not null);

A: Unfortunately not.
You can define two foreign key constraints, but they will both need to be valid for every row in the table.
The second problem is the choice of char datatype. No char(10) value in ORDERS will match a char(50) in either parent table. Probably the person who chose the data type was not familiar with it.

A: You can also create an insert and update Trigger on the ORDERS table to fulfill the requirement.
As per your comment, PART_NUM will be unique across two tables. So you can create the trigger as follows:
CREATE OR REPLACE TRIGGER ORDERS_TRG BEFORE
    INSERT OR UPDATE ON ORDERS
    FOR EACH ROW
DECLARE
    LV_COUNT   NUMBER;
BEGIN
    SELECT
        1
    INTO LV_COUNT
    FROM
        DUAL
    WHERE
        :NEW.PART IN (
            SELECT
                PART_NUM
            FROM
                PARTS_INV
            UNION ALL
            SELECT
                PART_NUM
            FROM
                PARTS_NONINV
        );

EXCEPTION
    WHEN NO_DATA_FOUND THEN
        RAISE;
END ORDERS_TRG;
/

db<>fiddle demo
Update the exception-handling part according to your requirement.
Cheers!!


text:
Q: PostgreSQL 9.6 version server unintentionally upgraded to version 14.5, now database cannot start, what to do? This is not a production system but it happened on my development laptop. I have PostgreSQL running on cygwin basis on a Windows 10 platform. The other day I was going to just add some other cygwin binary, but while doing so, the entire software suite was updated to the latest versions of everything. Now my postgresql system runs at version 14.5.
My dilemma is this: I could just cut my losses and throw away the database cluster and start over from scratch. But I might spend 2 or 3 days to recover from all the things that I would need to have back. A lot of work I am not even sure what would have been lost.
Size of the database on disk is about 8 GB. A bit heavy to move to some Unix system in the cloud to try and mount it from there pull a backup, and replay it all.
Is there any tool that I could use to just read the raw tuples to just look around and possibly recover some bigger tables that are worth not rebuilding from scratch?

A: Well it's hard to tell what happened. I have no idea what cygwin does. I have no idea how Postgres is started in cygwin. Whatever you use maybe tries to start 14, but some (unknown) configuration file points to the data directory of 9.6.
Something like the following should work.
Find out which configuration file in cygwin configures/controls how Postgres is started and what it thinks where the data directory is located. Then change this to make it start 9.6 with the (hopefully still existing) 9.6 data directory. Make a backup of the database  (pg_dumpall --globals-only to dump the user definitions, pg_dump to backup the data).
Then properly initialize a (new) data directory for 14 using its initdb binaries. Change those configuration files again to start the 14 binaries with the newly created data directory and then restore the dumps taken in the previous step.
While you are at it, it might be better to dump the cygwin solution and use the native Windows binaries instead.

A: Probably the new software was installed, but the server was not upgraded; look into the PostgreSQL log to be certain. You have to install PostgreSQL 9.6 again, perhaps from source, start the 9.6 server on the existing data directory and pg_dumpall the cluster. Run initdb from v14 to create a new cluster, start the server and import the dump. Then you have upgraded the database and can get rid of the old data directory and the old software.


text:
Q: How to calculate running total in SQL I have my dataset in the given format
It's a month level data along with salary for each month.
I need to calculate cumulative salary for each month end. How can I do this
+----------+-------+--------+---------------+
| Account  | Month | Salary | Running Total |
+----------+-------+--------+---------------+
| a        |     1 |    586 |           586 |
| a        |     2 |    928 |          1514 |
| a        |     3 |    726 |          2240 |
| a        |     4 |    538 |           538 |
| b        |     1 |    956 |          1494 |
| b        |     3 |    667 |          2161 |
| b        |     4 |    841 |          3002 |
| c        |     1 |    826 |           826 |
| c        |     2 |    558 |          1384 |
| c        |     3 |    558 |          1972 |
| c        |     4 |    735 |          2707 |
| c        |     5 |    691 |          3398 |
| d        |     1 |    670 |           670 |
| d        |     4 |    838 |          1508 |
| d        |     5 |   1000 |          2508 |
+----------+-------+--------+---------------+

I need to calculate running total column which is cumulative column. How can I do efficiently in SQL?

A: You can use SUM with ORDER BY clause inside the OVER clause:
SELECT Account, Month, Salary,
       SUM(Salary) OVER (PARTITION BY Account ORDER BY Month) AS RunningTotal
FROM mytable


text:
Q: SQL Trigger not pulling associated data I think I am so close on getting this trigger to work, but not yet. A SalesOrderLine (SOL) contains a Note field with a value.  Upon creating a PurchaseOrderLine (POL) which is linked as described below, I desire the SOL.Note to be copied to the POL.Note  The SOL and the POL are not directly linked, but rather they are linked via sub-tables (SOLD & POLD).
What I have so far is as follows:
Alter Trigger trInsertPOLNotes
on PurchaseOrderLine
After Insert
AS
BEGIN
SET NOCOUNT ON;
Update PurchaseOrderLine
set Notes = SOL.Notes
from  PurchaseOrderLine POL INNER JOIN
PurchaseOrderLineDetail POLD ON POL.LineId = POLD.LineId INNER JOIN
SalesOrderLineDetail SOLD ON POLD.SalesDetailId = SOLD.DetailId INNER JOIN
SalesOrderLine SOL on SOL.LineId = SOLD.LineId
END

Yes it kind of works, but the POL.Note is being populated with Note from a random SOL, not the
specific Note from the linked Sales Order Line.  Any help would be appreciated.


text:
Q: getRootNode() is not a function I try to develop an app with MVC architecture. I've the following Controller code:
Ext.define('PM.controller.Projects', {
    extend: 'Ext.app.Controller',

    models: ['Project'],
    stores: ['Projects'],

    views: [
        'projects.Tree',
        'Toolbar',
    ],

    init: function(config) {
        var tree = this.getProjectsTreeView();
        var rootNode = tree.getRootNode();
        console.log(rootNode);
        this.callParent(config);
    }
});

And this view code:
Ext.define('PM.view.projects.Tree', {
    extend: 'Ext.tree.Panel',
    xtype: 'projectsTree',

    title: 'Projects',
    hideHeaders: true,
    root: {
        text: "Projekte"
    }

});

It try to get the root node from my tree view in the controller but I get the error that getRootNode() is not a valid function in my controller. Can anybody tell me why I get this error? My target is to add new children to this root node from an ajax request.
Thanks

A: The methods Ext generates for each string in the views array return constructors that can be used to create the respective views. That seems bizarre, but that's how it is.
If you want to access the actual view component, you'll need to create a ref for it. Your init method should not assume that the view exists yet. It's very likely that it won't since the controller's init method is called before the application's launch method which is probably where all the views are getting added to the page.
You want to put your logic in the controller's onLaunch template method which is called after the application has been launched and your view has been added.
Ext.define('PM.controller.Projects', {
    extend: 'Ext.app.Controller',

    refs: [{
        ref: 'projectsTreeView',
        selector: 'projectsTree'
    }],

    init: function() {
        // It's safe to add selectors for views that don't exist yet.
        this.control(/*...*/)
    },

    onLaunch: function(config) {
        var tree = this.getProjectsTreeView();
        var rootNode = tree.getRootNode();
        console.log(rootNode);
    }
});

If this doesn't work, that means you aren't actually adding your view anywhere. One place you could add it is in the application's launch method. Something has to add the treeview.
Ext.application({
    // ...

    views: ['projects.Tree']

    launch: function() {
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [new this.getProjectsTreeView()]
        });
    }
});

So the chronology of events is this:
Application#constructor
Controller#constructor
Controller#init (can't assume the view exists)
Application#onBeforeLaunch
Application#launch (view is now added)
Controller#onLaunch (do something with the view that is now available)

Also, your view alias may need to be 'widget.projectsTree' not just 'projectsTree'.


text:
Q: How to pass multiple objects of same model type from view to controller? I am working in ASP.NET MVC 5 and am trying to post a form back to the controller. The form basically has several repeating textboxes that . I am trying to reuse the one model for each repeating form so I don't have to make a new field for each text box there is.
Model:
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

The part of my view where I am model binding text boxes (this is under @html.beginform)
@using (Html.BeginForm("PeronSave", "Home", FormMethod.Post, new { id = "PersonForm" }))
Person 1
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.TextBoxFor(m => m.Age, new { @class = "form-control" })

Now I want to have several of these groups of text boxes, so there would be Person1, Person2, Person3 etc. Is there a way I can send a list of type Person back to the controller?
I have tried changing using a foreach loop in the view but it doesn't have the desired result.

A: If you want to pass list of type of Person to the backend, You need to add index to each property. Please refer to this simple demo:
Here I use @for(xx)  to create three Person inputs and add index to each property:
@model List<Person>

@using (Html.BeginForm("PeronSave", "Home", FormMethod.Post, new { id = "PersonForm" }))
{
    @for (int i = 0; i < 3; i++)
    {
        Person @(i+1)
        @Html.TextBoxFor(m => m[i].Name, new { @class = "form-control" })
        @Html.TextBoxFor(m => m[i].Age, new { @class = "form-control" })
    }

    <button type="submit">submit</button>
}

The Page looks like:

Then I pass it to the backend and the controller can receive data successfully.


text:
Q: How to post to a facebook group wall in offline mode using graph API? (I am a member of group) I am trying to post a status update on the wall of a group which I am a member of. Here is the code I am using
            <?php
            require 'facebook-php-sdk/src/facebook.php';
            $appId = 'xxxxxxxxxxxxxxxx';
            $appSecret = 'xxxxxxxxxxxxxxxx';
            $extended_access_token = 'xxxxxxxxxxxxxxxxxxxxx';

            $facebook = new Facebook(array('appId' => $appId, 'secret' => $appSecret));

            $msg_body = array(
                'message' => 'Good evening',
                'type' => 'status',
                'access_token' => $extended_access_token,
            );

            $groups = array(
                            'Group name' => '1234567',
                        );
            foreach($groups as $group_name => $group_id){
                try {
                    $post_url = "/$id/feed";
                    $postResult = $facebook->api($post_url, 'post', $msg_body );
                    print_r($postResult);
                } catch (FacebookApiException $e) {
                    echo $e;
                }
            }
            ?>

If I login to fb via browser and hit this page in a new tab, the message is getting posted to the group wall. But If I am not logged into facebook, then if I hit this page, no message is getting posted and I am getting an error message
OAuthException: (#200) The user hasn't authorized the application to perform this action

How can I post to this group via offline mode? Searched a lot for this, could not find any useful info.

A: you need to have the permissions from the group owner

A: Change $id to $group_id and you'll be fine.

A: you ned to get apps this permession : publish_actions,publish_stream,user_groups,


text:
Q: Plot a 3-cycle graph with clockwise-directed edges When I try to plot a 3-cycle, the edge direction is always counter-clockwise. The plotting code is
GraphPlot[{1 -> 0, 0 -> 2, 2 -> 1}, VertexLabeling -> True,
 DirectedEdges -> True, PlotStyle -> {FontSize -> 13},
 VertexRenderingFunction -> ({EdgeForm[White],
     RGBColor[113/255, 190/255, 236/255], Disk[#1, 0.15], White,
     Text[#2, #1]} &)]

and the output

I have tried many ways to change the edge direction without success. Anyone can help with this? Thank you!

A: You can use the option VertexCoordinateRules:
opts = {VertexLabeling -> True, DirectedEdges -> True,
   VertexCoordinateRules -> {{0., 1.}, {1., 1.}, {.5, 0.}},
   PlotStyle -> {FontSize -> 13},
   VertexRenderingFunction -> ({EdgeForm[White],
       RGBColor[113/255, 190/255, 236/255], Disk[#1, 0.15], White,
       Text[#2, #1]} &)};
GraphPlot[{1 -> 0, 0 -> 2, 2 -> 1}, opts]

Or use Graph and give the vertices in the order you wish as the first argument:
opts2 = {VertexSize -> Medium,
   VertexStyle ->
    Directive[EdgeForm[White], RGBColor[113/255, 190/255, 236/255]],
   VertexLabels -> Placed["Name", Center],
   VertexLabelStyle -> {Directive[White, FontSize -> 16]},
   VertexShapeFunction -> "Circle"};
Graph[{0, 1, 2}, {1 -> 0, 0 -> 2, 2 -> 1}, opts2]

A: Simply as an alternative you can interactively rearrange the nodes, but to do so you must avoid VertexRenderingFunction.  Here is an example:
postLabel[f_] := Text[Framed[n_, __], p_] :> f[p, n]

labelFn = {EdgeForm[White], RGBColor[113/255, 190/255, 236/255], Disk[#1, 0.15], White,
    Text[#2, #1]} &;

GraphPlot[{1 -> 0, 0 -> 2, 2 -> 1}, VertexLabeling -> True, DirectedEdges -> True,
  PlotStyle -> {FontSize -> 13}] /. postLabel[labelFn]

You can then click as necessary to enter the graphic and select a node, then drag to rearrange as desired.  Example result:

Reference: https://stackoverflow.com/a/8109449/618728

A: You can use Graph and set explicit VertexCoordinates.
g = CycleGraph[3,
  PlotTheme -> "CoolColor",
  VertexLabelStyle -> Directive[Large, White],
  VertexSize -> 0.3,
  VertexLabels -> Placed["Name", Center],
  DirectedEdges -> True
 ]

{Graph[g, VertexCoordinates -> CirclePoints[3]],
 Graph[g, VertexCoordinates -> Reverse@CirclePoints[3]]}


text:
Q: Editing local Windows Firewall Policy via Powershell I'm writing a large script that goes through and applies a load of local policy settings via Powershell. Most of this is done by exporting the current security config via Secedit, passing this to an arraylist, adding/updating values as needed, then exporting the arraylist and importing back using Secedit.
My issue is that I need to set the local Firewall policy (Computer Configuration\Policies\Windows Settings\Security Settings\Windows Firewall with Advanced Security\Windows Firewall with Advanced Security\Windows Firewall Properties\Domain Profile\Firewall state) and this has caused me to get stuck.
I am able to manipulate the Local Firewall settings using
   $Domain = Get-NetFirewallProfile -name domain
   $domain | Set-NetFirewallProfile -DefaultInboundAction allow

But this is not manipulating the Policy.
I am also able to manipulate the registry keys that get written/updated when the policy is changed, however changing these does not show the Policy as changing for example:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile\enablefirewall=4,1

Changed to:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile\enablefirewall=4,0

Does not show the policy as changed, if a gpupdate /force is run - this setting gets wiped (from memory this is because the Policy is contained in the security DB under c:\windows\security)
I've tried adding in the Reg Key to the file that is imported via secedit - which successfully loads but does not manipulate the setting.
I've tried using open-netgpo - but I am unable as this is not a Domain joined machine (and will never be Domain joined) and I cannot pass a valid option for policystore in order to get it to manipulate the local Firewall policy
I would ideally like to have this controlled via the Local Policy as opposed to just the active Firewall setting.
I am hoping that there is a way to change the Firewall policy using Powershell so I can complete what I need to in an automated manner.
Thanks

A: Try cmd utility netsh
netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound


text:
Q: Legendre symbol related-problem Suppose that I am given an odd prime $p$. In addition, suppose that
$$\left(\dfrac{75}{p}\right) = -1, \left(\dfrac{93639}{p}\right) = 1.$$
I am solving for $\left(\dfrac{4179}{p}\right).$
I have utilized the Legendre symbol, so this does not mean division. I was trying to see if there were any relations between $4179,75,$ and $93639$, such as multiplying $4179$ and $75$, but this did not work. so then, I began to find the prime factorization of $4179$ and got
$$4179 = 3 \cdot 7 \cdot 199$$
So we have
$$\left(\dfrac{4179}{p}\right) = \left(\dfrac{3}{p}\right) \left(\dfrac{7}{p}\right) \left(\dfrac{199}{p}\right).$$
Now,
$$\left(\dfrac{75}{p}\right) = \left(\dfrac{5}{p}\right) \left(\dfrac{5}{p}\right) \left(\dfrac{3}{p}\right) = \left(\dfrac{3}{p}\right) = -1.$$
So we have
$$\left(\dfrac{4179}{p}\right) = (-1) \left(\dfrac{7}{p}\right)\left(\dfrac{199}{p}\right)$$
Where can I go from here?
Major edit
It turns out that there was indeed a typo in the problem after all and my answer below will discuss how to carry out this problem correctly.

A: It turns out that there was a typo in the question, which caused some of us to be frustrated with the calculations, including myself. Here, instead of $4179$, it is $4719$ and we will see why this change in numbers is significant to our final result. We begin by factoring $4719$ into primes to yield
$$4719 = 3 \cdot 11^2 \cdot 13$$
Thus, we have
$$\left(\dfrac{4719}{p}\right) = \left(\dfrac{3}{p}\right) \left(\dfrac{11}{p}\right) \left(\dfrac{11}{p}\right) \left(\dfrac{13}{p}\right) = \left(\dfrac{3}{p}\right) \left(\dfrac{13}{p}\right)$$
Next, we do the prime factorization of $75$ and have
$$75 = 3 \cdot 5^2$$
Thus, we have
$$\left(\dfrac{75}{p}\right) = \left(\dfrac{3}{p}\right) \left(\dfrac{5}{p}\right) \left(\dfrac{5}{p}\right) =\left(\dfrac{3}{p}\right) = -1$$ since $\left(\dfrac{75}{p}\right)  = -1$ was by hypothesis. Thus, we have
$$\left(\dfrac{4719}{p}\right) = (-1) \left(\dfrac{13}{p}\right)$$
Now, we find the prime factorization of $93639$ to yield
$$93639 = 3 \cdot 7^4 \cdot 13$$.
Hence, we have
$$\left(\dfrac{93639}{p}\right) = \left(\dfrac{3}{p}\right) \left(\dfrac{7}{p}\right) \left(\dfrac{7}{p}\right) \left(\dfrac{7}{p}\right) \left(\dfrac{7}{p}\right) \left(\dfrac{13}{p}\right) = \left(\dfrac{3}{p}\right) \left(\dfrac{13}{p}\right)$$ but $\left(\dfrac{3}{p}\right)  = -1$ and $\left(\dfrac{93639}{p}\right) = 1$. Thus, we have
$$1 = -1 \left(\dfrac{13}{p}\right) $$
Thus, $\left(\dfrac{13}{p}\right) = -1$. Thus, we have
$$\left(\dfrac{4719}{p}\right) = (-1)(-1) = 1.$$
QED


text:
Q: Delegates and native methods Here is a piece of code:
private static bool CreateDelegates ()
{
     IntPtr ptr;

     //--- SoundTouch: createInstance

     ptr = Kernel32Methods.GetProcAddress (libHandle, "_soundtouch_createInstance@0");

     if (ptr != IntPtr.Zero)
     {
         createInstance = (st_createInstance) Marshal.GetDelegateForFunctionPointer
                          (ptr, typeof (st_createInstance));
     }

     //--- SoundTouch: destroyInstance

     ptr = Kernel32Methods.GetProcAddress (libHandle, "_soundtouch_destroyInstance@4");

     if (ptr != IntPtr.Zero)
     {
         destroyInstance = (st_destroyInstance) Marshal.GetDelegateForFunctionPointer
                           (ptr, typeof (st_destroyInstance));
     }
}

And there is many more assigments like above in this method. I want to create method like AssignProc (...) to reduce amount of code.
void AssignProc (string procName, Delegate d, Type??? )
{
    IntPtr ptr;

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName);

    if (ptr != IntPtr.Zero)
    {
        d = (Type???) Marshal.GetDelegateForFunctionPointer
                          (ptr, typeof (???));
    }
}

Where:
 private static st_createInstance        createInstance;

 [UnmanagedFunctionPointer (CallingConvention.StdCall)]
 private delegate IntPtr st_createInstance ();

Help?:)

A: I guess you want a generic method:
T CreateDelegate<T>(string procName) where T : class
{
    IntPtr ptr;

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName);

    if (ptr != IntPtr.Zero)
    {
        return (T)(object)Marshal.GetDelegateForFunctionPointer(ptr, typeof (T));
    }

    return null;
}

Unfortunately, you can't constrain T to a delegate, so you first have to cast the result of GetDelegateForFunctionPointer to object before casting it to T.
Usage:
createInstance = CreateDelegate<st_createInstance>("_soundtouch_createInstance@0");
destroyInstance = CreateDelegate<st_destroyInstance>("_soundtouch_destroyInstance@4");


text:
Q: Navigate through dictionary  c# What is the better way to Navigate through a dictionary  ? I used to use the code below when i had IDictionary:
Assume that I have IDictionary named freq
IEnumerator enums = freq.GetEnumerator();
while (enums.MoveNext())
{
    string word = (string)enums.Key;
    int val = (int)enums.Value;
    .......... and so on

}

but now, I want to do the same thing using dictionary

A: Well you could do the same thing with Dictionary, but it would be cleaner to use foreach in both cases:
foreach (var entry in dictionary)
{
    string key = entry.Key;
    int value = entry.Value;
    // Use them...
}

This is equivalent to:
using (var iterator = dictionary.GetEnumerator())
{
    while (iterator.MoveNext())
    {
        var entry = iterator.Current;
        string key = entry.Key;
        int value = entry.Value;
        // Use them...
    }
}

It's very rarely useful to explicitly call GetEnumerator and iterate yourself. It's appropriate in a handful of cases, such as when you want to treat the first value differently, but if you're going to treat all entries the same way, use foreach.
(Note that it really is equivalent to using var here, but not equivalent to declaring an IEnumerator<KeyValuePair<string, int>> - it will actually use the nested Dictionary.Enumerator struct. That's a detail you usually don't need to worry about.)

A: The foreach statement iterates automatically through enumerators.
foreach (KeyValuePair<string,int> entry in freq) {
    string word = entry.Key;
    int val = entry.Value;
    .......... and so on

}

A: The default enumerator from a foreach gives you a KeyValuePair<TKey, TValue>:
foreach (var item in dictionary)
// foreach (KeyValuePair<string, int> item in dictionary)
{
    var key = item.Key;
    var value = item.Value;
}

This simply compiles into code that works directly with the enumerator as in your old code.
Or you can enumerate the .Keys or .Values directly (but you only get a key or a value in that case):
foreach (var key in dictionary.Keys)

foreach (var val in dictionary.Values)

And or course linq works against dictionaries:
C# linq in Dictionary<>


text:
Q: Vercel deploy prebuilt command unable to find the directory of my vercel build output im trying to deploy my project to vercel using vercel deploy--prebuilt however, i keep getting faced with the below error.1
I've checked the path which it says is missing but i think it can be seen in the below image? Can anyone advise on how to deal with this?
2 Project runs fine locally and vercel build runs smoothly and produces the file shown in image 1.


text:
Q: Pandas - How can I set rules for selecting which duplicates to drop I have a dataset with values in the column and in the index datetime objects.
What I want to do is drop the values that have the same index (date&time), but I want to make a rule like:

I have two values for the same datetime, so I want to pick the one closer to number X. That number could be for example the mean value of the whole dataset.

The dataset looks like this (I did reset the index when trying to make it happen because I got an error for having multiple indices):
         index                  kwh
16391   2014-10-26 03:14:59     0.0514139
16392   2014-10-26 03:29:59     0.0323344
16393   2014-10-26 03:29:59     12.3
16394   2014-10-26 03:44:59     0.0595618
16395   2014-10-26 03:59:59     0.0338677

if X (for example mean value) is 0.05 then what I want to get back is
16391   2014-10-26 03:14:59     0.0514139
16392   2014-10-26 03:29:59     0.0323344
16393   2014-10-26 03:44:59     0.0595618
16394   2014-10-26 03:59:59     0.0338677

I have tried using groupby and apply in several different ways but I cant get it to work.
Any help please?

A: If you add a dist column to the DataFrame which measures the absolute distance
between kwh and X:
X = df['kwh'].mean()
df['dist'] = (df['kwh'] - X).abs()

then you can groupby index and find the unique integer indices with the minimum dist for each group:
idx = df.groupby(['index'])['dist'].transform(lambda x: x == x.min()).astype(bool)

Then you can select those rows using df.loc:
df.loc[idx]

If data contains (note the duplicate values of kwh for the same index):
         index                  kwh
16391   2014-10-26 03:14:59     0.0514139
16392   2014-10-26 03:29:59     0.0323344
16392   2014-10-26 03:29:59     0.0323344
16393   2014-10-26 03:29:59     12.3
16394   2014-10-26 03:44:59     0.0595618
16395   2014-10-26 03:59:59     0.0338677

then
import pandas as pd

df = pd.read_table('data', sep='\s{2,}')
print(df)
X = df['kwh'].mean()
df['dist'] = (df['kwh'] - X).abs()
idx = df.groupby(['index'])['dist'].transform(lambda x: x == x.min()).astype(bool)
print(df.loc[idx])

yields
                     index       kwh      dist
16391  2014-10-26 03:14:59  0.051414  2.033505
16392  2014-10-26 03:29:59  0.032334  2.052584
16392  2014-10-26 03:29:59  0.032334  2.052584
16394  2014-10-26 03:44:59  0.059562  2.025357
16395  2014-10-26 03:59:59  0.033868  2.051051

Note that by using transform here, we get a boolean mask which allows us to select all rows -- including those with duplicate values of kwh -- which have the minimum distance from X.

You could use del df['dist'] to drop the dist column when you no longer need it.


text:
Q: Adding a css class to a mat-select item In my Angular application, the user can 'strikethrough' a line in a table full of text inputs.
I show this with a text-decoration: line-through css class.
How can I add the text-decoration: line-through css class for a mat-select item?

A: I don't know how you handle the user's choice to do a strike-through on a cell, but if you have some trigger/event that you listen to (like click), you can either use a ngClass or change cell's style by accessing the DOM.

*

*If you want to use ngClass, and you dynamically build the table content, you might need to build an array of objects, containing cells' IDs (or some other unique property that each cell has) and keys for strike-through status, like: cellsStatus = [ {id: 1, struck: false}, {id: 2, struck: false} ]. Then, in a method handling the strike-through event you take the id of a cell in question and change its struck value to !struck. In your dynamically build table, you'll have something like [ngClass]="cellsStatus[index].struck? 'cssClassWithLine' : 'cssClassWithoutLine'" that will use one or the other cssClass depending on the value of cellsStatus[index].struck. Handling cellsStatus[index] here depends on the way you structured the table, and it might be more complex - would help to see the code in your template and ts that handles the table contents.

*If you want to access the DOM elements and change style, you - again - need ID of the cells, although in this case you won't need another var (like cellsStatus array). If you have IDs for cells, in the mentioned handler method for strike-through action, you can do:
let element = document.getElementById(id);
if(element.style.textDecoration == 'line-through')
    element.style.textDecoration = 'none';
else element.style.textDecoration = 'line-through';

Finally, it all depends on the structure of your table and how you get the data. If you share all the relevant code, we can work out the details :)


text:
Q: Why don't we use moveToFirst() in bindView? When implementing onLoadFinished(), it requires moveToFirst() to work well, but why isn't this required when implementing bindView() for CursorAdapter? And when to use it?
onLoadFinished:
@Override
public void onLoadFinished(@NonNull Loader loader, Cursor data) {
    if (data.moveToFirst()) {
        int nameColumnIndex = data.getColumnIndexOrThrow(PetEntry.COLUMN_PET_NAME);
        int breedColumnIndex = data.getColumnIndexOrThrow(PetEntry.COLUMN_PET_BREED);

        mNameEditText.setText(data.getString(nameColumnIndex));
        mBreedEditText.setText(data.getString(breedColumnIndex));

    }
}

bindView:
@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView name = view.findViewById(R.id.name);
    TextView summary = view.findViewById(R.id.summary);

    String nameString = cursor.getString(cursor.getColumnIndexOrThrow(PetEntry.COLUMN_PET_NAME));
    String summaryString = cursor.getString(cursor.getColumnIndexOrThrow(PetEntry.COLUMN_PET_BREED));

    name.setText(nameString);
    summary.setText(summaryString);
}

A: The API explicitly states in CursorAdapter.bindView:
@param cursor The cursor from which to get the data. The cursor is already moved to the correct position.
So the moveToFirst is already done for you. The action is needed to advance in the records returned from the query on the database. If no records are found, moveToFirst will return false as per API description: Move the cursor to the first row. This method will return false if the cursor is empty.
The onLoadFinished isn't a member of the CursorAdapter and thus not tailored to do so.
Regards, Mike


text:
Q: Common Lisp shared structure confusion I am reading the book Practical Common Lisp, and in the footnote5 of chapter22, page284, I saw a code snippet that made me confused.
I know that the variable list and tail have a list structure in common,
but I am confusing that since tail will be assigned the value of 'new' each time during the iteration, why (setf (cdr tail) new) would affect the state of the variable list?
(do ((list nil) (tail nil) (i 0 (1+ i)))
    ((> i 10) list)
  (let ((new (cons i nil)))
    (if (null list)
        (setf list new)
        (setf (cdr tail) new))
    (setf tail new)))

;;; => (0 1 2 3 4 5 6 7 8 9 10)

A: The invariant is that tail is always the last cons cell of list.
On each iteration, a new cons cell is created holding the new value as car.  The first time through, list is set to this cons cell, and tail too.  In all subsequent iterations, the new cons cell is appended by setting the cdr of the last cell to it, then setting tail to the new cell, to recreate the invariant.
After first iteration:
 [ 0 | nil ]
   ^- list
   ^- tail

After second:
 [ 0 | -]--->[ 1 | nil ]
   ^- list     ^- tail

Third:
 [ 0 | -]--->[ 1 | -]--->[ 2 | nil ]
   ^- list                 ^- tail

A: The do form in your example keeps a pointer to the tail cons to make appending an element to the end of the list a cheap operation. Otherwise one would need to traverse the list all the time to find the last cons - for example by using appendor nconc. Another way would be to collect new elements on the head and at the end to reverse the result list.
One would expect that the LOOP macro implements something efficient by transforming a higher level loop expression into efficient code.
The macro form
(loop for i upto 10 collect i)

might expand into something that works internally similar as your do example. The advantage of loop is that you don't need to implement the logic to track the tail, since that's what the macro should do for you.


text:
Q: Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93) Getting below error after installed latest node.js (v16.13.1)

Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
I have created static pages for my application and use sass and gulp

I have a static pages and using Sass in the page and use gulp to run on the browser.(npm install). Below are the version which worked my application:

*

*Node.js - 12.18.0

*gulp - "4.0.2"

*"gulp-sass": "4.1.0"

Package.json file
"scripts": {
              "start": "gulp watch"
    },
"dependencies": {
        "@fortawesome/fontawesome-free": "5.15.1",
        "@ttskch/select2-bootstrap4-theme": "^1.5.2",
        "bootstrap": "4.5.3",
        "bootstrap-datepicker": "^1.9.0",
        "jquery": "3.5.1",
        "jquery.easing": "^1.4.1",
        "select2": "^4.1.0-rc.0",
        "gulp": "4.0.2"
    },
    "devDependencies": {
        "browser-sync": "2.26.13",
        "del": "6.0.0",
        "gulp": "4.0.2",
        "gulp-autoprefixer": "7.0.1",
        "gulp-clean-css": "4.3.0",
        "gulp-header": "2.0.9",
        "gulp-plumber": "^1.2.1",
        "gulp-rename": "2.0.0",
        "gulp-sass": "4.1.0",
        "gulp-uglify": "3.0.2",
        "merge-stream": "2.0.0"
    }

Even using command npm rebuild node-sass is not changing anything.

A: gulp-sass 4.1.0 uses node-sass 4, and node-sass 4 does not support Node.js 16, as indicated in this table.
To support Node.js 16, upgrade gulp-sass: the latest version today is 5.1.0:
npm install -D gulp-sass@5.1.0

This will give you node-sass 7, which supports all current versions of Node.js, including Node.js 16.


text:
Q: OnClick of button, Increase div it giving dynamic ID to each field in javascript I have a scenario where a User on button click can add upto 12 div's with same HTML. The html for the same is as below

    Terminated route name
    <input type="text" id="txtTerRouteName" />

    Cable Type
    <select id="ddlCableType">
            <option value="--Select--">--Select--</option>
      <option value="G652">G652</option>
      <option value="G655">G655</option>
        </select>

    Cable Size
    <select id="ddlCableSize">
            <option value="--Select--">--Select--</option>
            <option value="12F">12F</option>
            <option value="24F">24F</option>
            <option value="48F">48F</option>
    </select>

    No of Live Fibre
    <input type="text" id="txtNoLiveFibre" />

And the button is also below on which of the above whole div will get created again with dynamic ID's
ADD NPE +
<input type="button" id="btnAddNPE" value="Add NPE" onclick="addNPEInfo()" />

So for that I tried something like below..!
var div = document.getElementById('dvNPEInnerData'),
    clone = div.cloneNode(true);
 clone.id = "dvNPEInnerData1";
 //document.body.appendChild(clone);
 document.getElementById('dvNPEAddData').appendChild(clone);

The divs are generated properly, but the issue is the ID for each control like input = text and select is not been generated.

So how should I use this so that it can generate same html with dynamic ID's

A: Try following code.
var appendNewId=1;
function addNPEInfo(){
    if(appendNewId>12){
        alert("Maximum 12 rows allowed");
        return;
    }
    var div = document.getElementById('dvNPEInnerData'),
    clone = div.cloneNode(true);

    appendId(clone, "div", appendNewId);
    appendId(clone,"select", appendNewId);
    appendId(clone,"input", appendNewId);
    appendId(clone,"label", appendNewId);

    clone.id = "dvNPEInnerData"+appendNewId;
    //document.body.appendChild(clone);
    document.getElementById('dvNPEAddData').appendChild(clone);
    appendNewId++;
}
function appendId(clone,tag, id){
    var ele = clone.getElementsByTagName(tag);
    for(i in ele){
        ele[i].id = ele[i].id+id;
    }
}

Change value of appendNewId as per your need.


text:
Q: Alternatives to " " for creating strings containing multiple whitespace characters I'm wondering if there's a more OO way of creating spaces in C#.
Literally Space Code!
I currently have tabs += new String(" "); and I can't help but feel that this is somewhat reminiscent of using "" instead of String.Empty.
What can I use to create spaces that isn't " "?

A: if the number of spaces would be changing then you could do something like this:
public static string Space(int count)
{
    return "".PadLeft(count);
}

Space(2);

A: There is no reason to do this. All else being equal, smaller code is better code. String.Empty and new String(' ') communicate the same thing as "" and " ", they just take more characters to do it.
Trying to make it 'more OO' just adds characters for no benefit. Object-Orientation is not an end in itself.

A: You can write
" "

instead of
new String(' ')

Does that help?

Depending on what you do, you might want to look into the StringBuilder.Append overload that accepts a character and a 'repeat' count:
var tabs = new StringBuilder();
tabs.Append(' ', 8);

or into the string constructor that constructs a string from a character a 'repeat' count:
var tabs = new string(' ', 8);

Here's an enterprisey OO solution to satisfy all your space generation needs:
public abstract class SpaceFactory
{
    public static readonly SpaceFactory Space = new SpaceFactoryImpl();

    public static readonly SpaceFactory ZeroWidth = new ZeroWidthFactoryImpl();

    protected SpaceFactory { }

    public abstract char GetSpace();

    public virtual string GetSpaces(int count)
    {
        return new string(this.GetSpace(), count);
    }

    private class SpaceFactoryImpl : SpaceFactory
    {
        public override char GetSpace()
        {
            return '\u0020';
        }
    }

    private class ZeroWidthFactoryImpl : SpaceFactory
    {
        public override char GetSpace()
        {
            return '\u200B';
        }
    }
}

A: Depending on how prevalent this is in your code, the StringBuilder way may be better.
StringBuilder tabs = new StringBuilder();
...

tabs.Append(" ");

You can mix in the constant too...
StringBuilder tabs = new StringBuilder();
const string SPACE = " ";
...

tabs.Append(SPACE);

A: Extend string to give you a method to add space
public static string AddSpace(this String text, int size)
{
   return text + new string(' ', size)
}

Awful in it's own right though.

A: The more "OO" way would be to find a simpler way of solving your larger business problem. For example, the fact that you have a variable named tabs suggests to me that you are trying to roll your own column alignment code. String.Format supports that directly, e.g.
// Left-align name and status, right-align amount (formatted as currency).
writer.WriteLine("Name                 Status         Amount");
writer.WriteLine("-------------------- ---------- ----------");
foreach(var item in items) {
    writer.WriteLine(string.Format("{0,-20} {1,-10} {2,10:C}", item.Name, item.Status, item.Amount));
}

A: Now that you've clarified in comments:

In my actual code I'm doing new
  String(' ',numberOfSpaces) so I
  probably need to still use the new
  String part.

... the other answers so far are effectively useless :(
You could write:
const char Space = ' ';

then use
new string(Space, numberOfSpaces)

but I don't see any benefit of that over
new string(' ', numberOfSpaces)

A: If the language allowed for it you could add an extension property to the type String which was Space, something like:
public static class StringExt
{
    public static char Space(this String s)
    {
        get {
            return ' ';
        }
    }
}

but that isn't possible.  I think it would be better to keep the space inside the property if it was a localizable thingy, but I think spaces are universal across all languages.

A: I think you are taking OO way to far.. A simple addition of a space does not need an entire class.
tabs += new String(' ');

or
tabs += " ";

is just fine.

A: You could use "\t", I think, to give you a tab character. That might make the spaceing more clear.

A: StringBuilder.Insert and StringBuilder.Append allow you to create any number spaces, e.g. sb.Insert(0, " ", 20) will insert 20 spaces to the start of your sb (StringBuilder) object.

A: You may create class extensions.
public static class StringExtensions
    {
        public static string GetSpace(this String)
        {
           return " ";
        }
    }

and you can call this.
String.GetSPace();

A: I tend to use string.Empty.PadLeft(8) for example


text:
Q: How to POST Highcharts Image? I need to create a PDF file which contains Highcharts.js chart and just wondering if there is a way to optimize the Export module to POST the image (png or jpeg) to a PHP file which I want to create the PDF files there.
As you know the exporting module normally exports the output as downloadable files but I do not want to download them just send them on the server.
Thanks

A: You can use highchart's exporting module along with TCPDF Library. The TCPDF library Support svg rendaring.
You can use the exportApi
   chart.exportChart({
             url : 'export.php',
             filename: 'my-chart'
        });

Then use the example script a modified version from original SVG pdf example
Main part of the code is
$pdf->ImageSVG expect first parameter as string
Name of the SVG file or a '@' character followed by the SVG data string.

$pdf->ImageSVG("@".$_POST['svg'], $x=15, $y=30, $w=200);

Happy coding!!
NB: You need to download the TCPDF library


text:
Q: Hierarchical query - show parent name when all children present The problem
I'm struggling with a hierarchical problem with Postgres.
I have multi-level hierarchical structure (let's assume 3 for purpose of the question)
-> category
--> subcategory
---> item

Those are different tables but I can simply convert it into one child-parent table / CTE. Each of the parent category can have multiple children.
And I have another table, let's say UserPreferences, where there is a relation between User and Items (which Items user selected as preferences).
What I need to do is create a query that will return all user preferences BUT there is a requirement that if all nodes under the parent are selected, then parent name should be presented instead of the list of children.

Example
if we have following situation:
-> category 1
--> subcategory 1
---> item 1 (selected by user)
---> item 2 (selected by user)
--> subcategory 2
---> item 3 (selected by user)
---> item 4
-> category 2
--> subcategory 3
---> item 5 (selected by user)

Then the desired output for user is:
subcategory 1, item 3, category 2
Note that the query should allow to query for multiple users at once so function is not an option.

Attempts
I had multiple attemps on writing such query using:

*

*recursive CTE - I had problems with writing the proper condition though :/ I'm also a bit worried about the performance - if it will be good enough

*group by ROLLUP + some left lateral joins to get counts within categories - but here I had problems in a situation presented with "category 2" - so that in my case "category 2" and "subcategory 2" would be presented instead of only "category 2"

Does anyone have any suggestions what would be the best approach for this?

A: You should have a database design that represent this hierachy with intervals instead of nested set. Then the query will be simple...
I wrote some papers about that:
https://sqlpro.developpez.com/cours/arborescence/#LII
But it is in french...
The query to find the upper level when all subitems are checked is :
SELECT *
FROM   INTERVAL_TREE AS IT
WHERE  (RIGHT_BOUND - LEFT_BOUND) / 2 =
       (SELECT COUNT(*)
        FROM   INTERVAL_TREE
        WHERE  CHECKED = 1
          AND  RIGHT_BOUND > IT.RIGHT_BOUND
          AND  LEFT_BOUND < IT.LEFT_BOUND)

Off course the predicate "CHECKED = 1" can be a subquery...


text:
Q: Not able to Scrape through BeautifulSoup I am trying to scrape image and news url from this website. The tag which i have defined is
root_tag=["div", {"class":"ngp_col ngp_col-bottom-gutter-2 ngp_col-md-6 ngp_col-lg-4"}]
image_tag=["div",{"class":"low-rez-image"},"url"]
news_url=["a",{"":""},"href"]

and url is url ,my code for scraping the website is.
ua1 = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
ua2 = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome'
headers = {'User-Agent': ua2,
           'Accept': 'text/html,application/xhtml+xml,application/xml;' \
                     'q=0.9,image/webp,*/*;q=0.8'}
session = requests.Session()
response = session.get(url, headers=headers)
webContent = response.content
bs = BeautifulSoup(webContent, 'lxml')
all_tab_data = bs.findAll(root_tag[0], root_tag[1])

result=[]
for div in all_tab_data:
    try:
        news_url=None
        news_url = div.find(news_tag[0], news_tag[1]).get(news_tag[2])

    except Exception as e:
        news_url= None

    try:
        image_url = None
        div_img = str(div)
        match = re.search(r"(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png|jpeg)", div_img)
        if match != None:
            image_url = str(match.group(0))
        else:
            image_url = div.find(image_tag[0], image_tag[1]).get(image_tag[2])

    except Exception as e:
        image_url=None
        pass
    result.append([news_url,image_url])

I debug the code and find that all_tab_data is empty but i am choosing correct root_tag. So i dont know what i am doing wrong

A: The content is loaded from a JSON.
You can get all the image urls this way:
import requests

url = "https://www.nationalgeographic.com/magazine/_jcr_content/content/promo-carousel.promo-carousel.json"

data = requests.get(url).json()

for item in data:
    for sub_item in item['promo_carousel']:
        p_img = sub_item['promo_image']
        if p_img is not None:
            print(p_img['image']['uri'])

Output:
https://www.nationalgeographic.com/content/dam/animals/2020/09/african-cheetah-snow/african-cheetah-snow-2.jpg
https://www.nationalgeographic.com/content/dam/animals/2020/09/wallaby-atrazine/wallaby-og-a0xh8r-01.jpg
https://www.nationalgeographic.com/content/dam/animals/2020/09/elephant-tuberculosis/r40bfj.jpg
https://www.nationalgeographic.com/content/dam/animals/2020/08/handfish/01-handfish-minden_90392182.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/08/cal-fire-update/california-fire-palley-mm9468_200905_000229.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/11/face-mask-recognition/20200901_002_out_mp4_00_00_03_18_still003.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/10/winds-fires-california/winds-fires-california-2019.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/10/fire-air-quality/fire-air-pollution-20253854760329.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/02/autopsy/mm9412_200717_000522.jpg
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/explore/stellar-map-milky-way-og.png
https://www.nationalgeographic.com/content/dam/science/2020/07/31/vaccine/vaccine_20209514426186.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/rights-exempt/history-magazine/2020/09-10/metric-system/og-french-metric-system.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/rights-exempt/OG/red-terror-explainer-og.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/rights-exempt/OG/promo-medieval-pandemic.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/2020/09/Asian-American-COVID/og_asianamerican.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/2020/08/goodbye-hong-kong/19-hong-kong-security-law-china.jpg
https://www.nationalgeographic.com/content/dam/travel/commercial/2020/samsung/wyoming/samsung-wyoming-mountain.jpg
https://www.nationalgeographic.com/content/dam/travel/2020-digital/kissing-tourism-sites/gettyimages-3332297.jpg
https://www.nationalgeographic.com/content/dam/travel/2020-digital/thinking-about-traveling/nationalgeographic_1085186.jpg
https://www.nationalgeographic.com/content/dam/science/commercial/2019/domestic/wyss-foundation/wyss-foundation_cfn_natgeo-image-collection_1971120.jpg
https://www.nationalgeographic.com/content/dam/travel/2020-digital/least-visited-US-national-parks/nationalgeographic_2466315.jpg

EDIT: To get title and article data use this:
for item in data:
    for sub_item in item['promo_carousel']:
        print(f"{sub_item['components'][0]['title']['text']}"
              f"\n{sub_item['uri']}")
        p_img = sub_item['promo_image']
        if p_img is not None:
            print(f"{p_img['image']['uri']}")
        print("-" * len(sub_item['uri']))

Prints (shortened for brevity):
Rare photographs show African cheetahs in snowstorm
https://www.nationalgeographic.com/animals/2020/09/cheetahs-snow-south-africa/
https://www.nationalgeographic.com/content/dam/animals/2020/09/african-cheetah-snow/african-cheetah-snow-2.jpg
------------------------------------------------------------------------------
Wallabies exposed to common weed killer have reproductive abnormalities
https://www.nationalgeographic.com/animals/2020/09/wallaby-sexual-development-impaired-by-atrazine-herbicide/
https://www.nationalgeographic.com/content/dam/animals/2020/09/wallaby-atrazine/wallaby-og-a0xh8r-01.jpg
-------------------------------------------------------------------------------------------------------------
...

A: Another solution:
import json
import requests
from bs4 import BeautifulSoup

url = 'https://www.nationalgeographic.com/magazine/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
data = json.loads( soup.select_one('[data-pestle-module="Lead"] [data-pestle-options]').string )

# to print all data uncomment next line:
# print(json.dumps(data, indent=4))

for b in data['body']:
    if 'multilayout_promo_beta' not in b:
        continue

    for s in b['multilayout_promo_beta']['stories']:
        if not s.get('lead_media'):
            continue
        if 'immersive_lead' not in s['lead_media']:
            print(s['components'][0]['title']['text'])
            print(s['lead_media']['image']['uri'])
        else:
            print(s['lead_media']['immersive_lead']['title'])
            print(s['lead_media']['immersive_lead']['lead_media']['image']['uri'])
        print(s['uri'])
        print('-' * 80)

Prints:
America's neglected hiking trails are more popular than ever—but they're struggling
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/us-hiking-trails/us-hiking-trails-campfire-valley.jpg
https://www.nationalgeographic.com/magazine/2020/10/america-long-neglected-hiking-trails-are-more-popular-than-ever-but-they-are-struggling-feature/
--------------------------------------------------------------------------------
The heroic effort in the Amazon to save one of the world's largest eagles
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/saving-largest-eagle/harpy-eagles-brazil-14a.jpg
https://www.nationalgeographic.com/animals/2020/04/saving-worlds-largest-eagle/
--------------------------------------------------------------------------------
The robot revolution has arrived
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/rise-of-the-machines/mm8612_190408_00122-3.jpg
https://www.nationalgeographic.com/magazine/2020/09/the-robot-revolution-has-arrived-feature/
--------------------------------------------------------------------------------
They may look goofy, but ostriches are nobody's fool
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/ostriches/ostriches-standing-tall-male-beach.jpg
https://www.nationalgeographic.com/magazine/2020/09/they-may-look-goofy-but-ostriches-are-nobodys-fool-feature/
--------------------------------------------------------------------------------
The Great Lakes depend on ice. This winter, they barely froze.
https://www.nationalgeographic.com/content/dam/science/2020/03/19/no-ice/year-with-no-ice-sacka-46.jpg
https://www.nationalgeographic.com/science/2020/03/great-lakes-depend-on-winter-ice-low-cover/
--------------------------------------------------------------------------------
'I put my camera to my face and cried.' Documenting a COVID-19 hot spot
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/coronavirus/departements-detroit-singer-funeral.jpg
https://www.nationalgeographic.com/magazine/2020/10/danny-wilcox-frazier-on-photographing-covid-19-in-detroit/
--------------------------------------------------------------------------------
COVID-19's impact on the animal kingdom—so far
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/coronavirus/departments-covid-animals-tiger.jpg
https://www.nationalgeographic.com/magazine/2020/10/covid-19s-impact-on-the-animal-kingdom-so-far/
--------------------------------------------------------------------------------
To prevent the next deadly disease, we must stop harming nature
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/departments/coronavirus/departments-coronavirus-coral-reef.jpg
https://www.nationalgeographic.com/magazine/2020/09/pristine-seas-enric-sala-we-must-stop-harming-nature-to-prevent-deadly-disease-coronavirus/
--------------------------------------------------------------------------------
Beyond masks and gloves—here's how the pros handle dangerous microbes
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/departments/coronavirus/tool-kit-covid-testing.jpg
https://www.nationalgeographic.com/magazine/2020/09/beyond-masks-and-gloves-here-is-how-the-pros-handle-dangerous-microbes/
--------------------------------------------------------------------------------
NASA sent a map to space to help aliens find Earth. Now it needs an update.
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/explore/departments-stellar-map-galaxy.jpg
https://www.nationalgeographic.com/magazine/2020/10/nasa-sent-a-map-to-space-to-help-aliens-find-earth-now-it-needs-an-update/
--------------------------------------------------------------------------------
This archaeologist hunts DNA from prehistoric diseases
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/coronavirus/departments-genius-rifkin.jpg
https://www.nationalgeographic.com/magazine/2020/10/archaeologist-riaan-rifkin-hunts-dna-from-prehistoric-diseases/
--------------------------------------------------------------------------------
See the ingenious cameras used to photograph elusive animals
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/explore/departments-artifact-crittercam-wooden-fin.jpg
https://www.nationalgeographic.com/magazine/2020/10/see-the-ingenious-crittercams-used-to-photograph-elusive-animals/
--------------------------------------------------------------------------------
Popsicles and belly rubs: The joys of watching a panda grow up
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/departments/explore/explore-essay-panda-stretching.jpg
https://www.nationalgeographic.com/magazine/2020/09/popsicles-and-belly-rubs-the-joys-of-watching-panda-bei-bei-grow-up/
--------------------------------------------------------------------------------


text: Q: Variable importance in cases of multicollinearity: OLS vs ridge regression I have read that when using Ordinary Least Squares (OLS) for multiple linear regression, the coefficients/weights are unreliable for predictor variables that are collinear. I was wondering if this is also the case for regularisation methods (ridge/lasso/elastic net regression) when variables are collinear? Or could the coefficients/weights be used to determine relative importance of the predictors?


text:
Q: How to retrieve the current background-image value of an element with IE6? This is a bit maddening.  I have code which saves the current background-image from a selected element into a variable, which I then use to create an img tag.
Simply put, the following works in all browsers I've tested except IE6:
var bg = $('.element_selector').css('background-image');

The return value from IE6 is 'none', which is incorrect.  (Before anyone suggests trying 'backgroundImage' instead of 'background-image', no dice.)
Any ideas on how I can get that value?
Update: I forgot to mention that the background image in question was processed by DD_belatedPNG, which now appears to be the culprit -- if I comment out the fix, I get my value.  If anyone knows offhand how I could still fetch that value after the png fix is in, please let me know.

A: *

*Have you tried background?

*Are you sure the element is right?

A: After some testing in IE6 I was able to reproduce your issue with DD_belatedPNG and background src.
Here's what I've found.  If you set the background-image variable before calling DD_belatedPNG.fix('[selector]'); then you get the desired result.  If you're setting it afterward for instance in a click event you get a value of "none".
Additionally, DD_belatedPNG adds an image element to the page containing your background image (with a class of DD_belatedPNG_sizeFinder), so you can potentially 1) re-use, 2) copy, or 3) take src attribute value from that element.
Here's my testing code:
CSS:
#myElement
{
    width: 515px;
    height: 341px;
    margin: 100px auto;
    background: #f00 url('http://www.chismbrothers.com/images/woodfloors.png') no-repeat 0 0;
}

HTML:

jQuery:
$(document).ready(function() {
    // Works as expected
    var bg = $('#myElement').css('background-image');
    $('#test1').text("pre png fix: " + bg);

    DD_belatedPNG.fix('#myElement');

    $('#myElement').click(function() {
        var bg = $(this).css('background-image');
        var bgAll = $(this).css('background');

        // This yields values of 'none' for bg and 'undefined' for bgAll
        $('#test2').html("post png fix: " + bg + "
bg: " + bgAll);

        // DD_belatedPNG creates an image element on the page with a class of
        // 'DD_belatedPNG_sizeFinder' which can be used to get the image src
        $('#test3').html('dd_belatedpng_sizeFinder: ' + $('.DD_belatedPNG_sizeFinder').attr("src"));

        // Perhaps reapplying 'zoom' css will reapply the BG values?
        $(this).css({ zoom: 0 }).css({ zoom: 1 });
        // Set values again.
        bg = $(this).css('background-image');
        bgAll = $(this).css('background');
        // No luck...same result as #test2
         $('#test4').html("post png fix: " + bg + "
bg: " + bgAll);
    });
});